"""项目成员管理API路由"""
from __future__ import annotations

from fastapi import APIRouter, Depends, Query, Request
from motor.motor_asyncio import AsyncIOMotorDatabase

from app.api.deps import get_current_user, get_db
from app.core.response import (
    ErrorMessages,
    ErrorTypes,
    error_response,
    paginated_response_with_stats,
    success_response,
)
from app.schemas.team_member import TeamMemberCreateRequest, TeamMemberUpdateRequest
from app.services.team_member_service import team_member_service


router = APIRouter()


@router.get("", summary="获取团队成员列表")
async def list_team_members(
    request: Request,
    project_id: str | None = Query(None, description="项目ID过滤"),
    role: str | None = Query(None, description="项目角色过滤"),
    status: str | None = Query(None, description="成员用户状态过滤"),
    keyword: str | None = Query(None, description="搜索关键字"),
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=200, description="每页条数"),
    sort_by: str = Query("joined_at", description="排序字段"),
    sort_order: int = Query(-1, description="排序方向，1或-1"),
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db),
):
    """分页获取团队成员数据"""

    try:
        result = await team_member_service.list_team_members(
            db=db,
            current_user=current_user,
            project_id=project_id,
            role=role,
            status=status,
            keyword=keyword,
            page=page,
            size=size,
            sort_by=sort_by,
            sort_order=sort_order,
        )

        return paginated_response_with_stats(
            items=[record.model_dump() for record in result.items],
            total=result.total,
            page=result.page,
            size=result.size,
            statistics=result.statistics.model_dump(),
            request_id=getattr(request.state, "request_id", None),
        )
    except PermissionError as exc:
        return error_response(
            error_type=ErrorTypes.PERMISSION_DENIED_ERROR,
            message=str(exc) or ErrorMessages.PERMISSION_DENIED,
            code=403,
            request_id=getattr(request.state, "request_id", None),
        )
    except ValueError as exc:
        return error_response(
            error_type=ErrorTypes.VALIDATION_ERROR,
            message=str(exc),
            code=400,
            request_id=getattr(request.state, "request_id", None),
        )
    except Exception as exc:  # noqa: BLE001
        return error_response(
            error_type=ErrorTypes.INTERNAL_ERROR,
            message=f"Failed to fetch team members: {exc}",
            code=500,
            request_id=getattr(request.state, "request_id", None),
        )


@router.post("", summary="添加团队成员")
async def add_team_member(
    request: Request,
    payload: TeamMemberCreateRequest,
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db),
):
    """添加团队成员"""

    try:
        await team_member_service.add_team_member(db=db, current_user=current_user, payload=payload)
        return success_response(
            message="Member added successfully",
            request_id=getattr(request.state, "request_id", None),
        )
    except PermissionError as exc:
        return error_response(
            error_type=ErrorTypes.PERMISSION_DENIED_ERROR,
            message=str(exc) or ErrorMessages.PERMISSION_DENIED,
            code=403,
            request_id=getattr(request.state, "request_id", None),
        )
    except ValueError as exc:
        return error_response(
            error_type=ErrorTypes.VALIDATION_ERROR,
            message=str(exc),
            code=400,
            request_id=getattr(request.state, "request_id", None),
        )
    except Exception as exc:  # noqa: BLE001
        return error_response(
            error_type=ErrorTypes.INTERNAL_ERROR,
            message=f"Failed to add member: {exc}",
            code=500,
            request_id=getattr(request.state, "request_id", None),
        )


@router.put("/{project_id}/{user_id}", summary="更新团队成员")
async def update_team_member(
    request: Request,
    project_id: str,
    user_id: str,
    payload: TeamMemberUpdateRequest,
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db),
):
    """更新团队成员信息"""

    try:
        await team_member_service.update_team_member(
            db=db,
            current_user=current_user,
            project_id=project_id,
            user_id=user_id,
            payload=payload,
        )
        return success_response(
            message="Member updated successfully",
            request_id=getattr(request.state, "request_id", None),
        )
    except PermissionError as exc:
        return error_response(
            error_type=ErrorTypes.PERMISSION_DENIED_ERROR,
            message=str(exc) or ErrorMessages.PERMISSION_DENIED,
            code=403,
            request_id=getattr(request.state, "request_id", None),
        )
    except ValueError as exc:
        return error_response(
            error_type=ErrorTypes.VALIDATION_ERROR,
            message=str(exc),
            code=400,
            request_id=getattr(request.state, "request_id", None),
        )
    except Exception as exc:  # noqa: BLE001
        return error_response(
            error_type=ErrorTypes.INTERNAL_ERROR,
            message=f"Failed to update member: {exc}",
            code=500,
            request_id=getattr(request.state, "request_id", None),
        )


@router.delete("/{project_id}/{user_id}", summary="移除团队成员")
async def remove_team_member(
    request: Request,
    project_id: str,
    user_id: str,
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db),
):
    """移除团队成员"""

    try:
        await team_member_service.remove_team_member(
            db=db,
            current_user=current_user,
            project_id=project_id,
            user_id=user_id,
        )
        return success_response(
            message="Member removed successfully",
            request_id=getattr(request.state, "request_id", None),
        )
    except PermissionError as exc:
        return error_response(
            error_type=ErrorTypes.PERMISSION_DENIED_ERROR,
            message=str(exc) or ErrorMessages.PERMISSION_DENIED,
            code=403,
            request_id=getattr(request.state, "request_id", None),
        )
    except ValueError as exc:
        return error_response(
            error_type=ErrorTypes.VALIDATION_ERROR,
            message=str(exc),
            code=400,
            request_id=getattr(request.state, "request_id", None),
        )
    except Exception as exc:  # noqa: BLE001
        return error_response(
            error_type=ErrorTypes.INTERNAL_ERROR,
            message=f"Failed to remove member: {exc}",
            code=500,
            request_id=getattr(request.state, "request_id", None),
        )



